package com.kuaimacode.kframework.api.controller.user;

import com.github.pagehelper.PageInfo;
import com.kuaimacode.kframework.api.controller.BaseController;
import com.kuaimacode.kframework.api.service.AddressService;
import com.kuaimacode.kframework.api.service.UserService;
import com.kuaimacode.kframework.api.vo.request.AddressReq;
import com.kuaimacode.kframework.common.Constant;
import com.kuaimacode.kframework.common.JsonResult;
import com.kuaimacode.kframework.constants.PageConstants;
import com.kuaimacode.kframework.exception.ErrorEnum;
import com.kuaimacode.kframework.exception.ServerInternalErrorException;
import com.kuaimacode.kframework.mybatis.models.user.Address;
import com.kuaimacode.kframework.mybatis.models.user.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/address")
@Api(tags = "用户地址",description = "用户地址相关api")
public class AddressRestController extends BaseController {

    @Autowired
    private AddressService addressService;
    @Autowired
    private UserService userService;


   /* @ApiOperation(value = "查询地址列表(分页)", notes="查询地址列表")
    @GetMapping("/listPage")
    public JsonResult<Address> index(@RequestParam(value = "pageNum", required = true, defaultValue = PageConstants.PAGE_NUM+"") int pageNum,
                        @RequestParam(value = "pageSize", required = true, defaultValue = PageConstants.PAGE_SIZE+"") int pageSize) {
        PageInfo<Address> pageInfo = addressService.findAll(pageNum, pageSize);
        return JsonResult.success(pageInfo.getList());
    }*/

    @ApiOperation(value = "查询常用地址列表(分页)", notes="查询常用地址列表(分页)")
    @GetMapping("/usualListPage")
    public JsonResult<Address> usualListPage(@RequestParam(value = "pageNum", required = true, defaultValue = PageConstants.PAGE_NUM+"") int pageNum,
                            @RequestParam(value = "pageSize", required = true, defaultValue = PageConstants.PAGE_SIZE+"") int pageSize) {
        PageInfo<Address> pageInfo = addressService.getAddressListPage(getUserId(),Constant.IsNotEnum.YES.getCode(),pageNum, pageSize);
        return JsonResult.success(pageInfo);
    }


    @ApiOperation(value = "查询常用地址列表", notes="查询常用地址列表")
    @GetMapping("/usualList")
    public JsonResult<Address> usualList(HttpServletRequest request){
        List<Address> list = addressService.getAddressList(getUserId(),Constant.IsNotEnum.YES.getCode());
        return JsonResult.success(list);
    }

    @ApiOperation(value = "查询用户地址列表", notes="查询用户地址列表")
    @GetMapping("/list")
    public JsonResult<Address> list(HttpServletRequest request){
        List<Address> list = addressService.getAddressList(getUserId(),null);
        return JsonResult.success(list);
    }

    @ApiOperation(value = "查询用户地址列表(分页)", notes="查询用户地址列表(常用和不常用地址)")
    @GetMapping("/addrListPage")
    public JsonResult<Address> listPage(@RequestParam(value = "pageNum", required = true, defaultValue = PageConstants.PAGE_NUM+"") int pageNum,
                                    @RequestParam(value = "pageSize", required = true, defaultValue = PageConstants.PAGE_SIZE+"") int pageSize) {
        PageInfo<Address> pageInfo = addressService.getAddressListPage(getUserId(),null,pageNum, pageSize);
        return JsonResult.success(pageInfo.getList());
    }



    @ApiOperation(value = "编辑地址", notes="编辑地址")
    @PostMapping("/edit")
    @ApiImplicitParams({
        //@ApiImplicitParam(name = "id", value = "地址ID", required = true, dataType = "long",paramType = "path"),
        @ApiImplicitParam(name = "address", value = "地址实体", required = true, dataType = "AddressReq")
    })
    public JsonResult edit(@Valid @RequestBody AddressReq address){
        Optional.ofNullable(address.getId()).orElseThrow(()-> new ServerInternalErrorException(ErrorEnum.DATA_NOT_EXIST));
        Address address1 = addressService.getById(address.getId());
        Optional.ofNullable(address1).orElseThrow(()-> new ServerInternalErrorException(ErrorEnum.DATA_NOT_EXIST));
        //校验detail中是否还有省市区
        // pattern = "/.*?省.*?市.*?区$/";
        //boolean isMatch = Pattern.matches(pattern, address.getDetail());
        String summarys = addressResolution(address.getDetail());
        if(summarys != null && summarys.length() > 0){
            String detail = address.getDetail().replace(summarys, "");
            address.setDetail(detail);
            address.setSummary(summarys);
            //throw new ServerInternalErrorException(ErrorEnum.PARAM_VALID_ERROR);
        }
        BeanUtils.copyProperties(address,address1);
        address1.setUpdateAt(new Date());
        //address.setUserId(getUserId());
        if(addressService.update(address1)){
            return JsonResult.success();
        }else{
            return JsonResult.failure("操作失败");
        }

    }

    @ApiOperation(value = "新增地址", notes="新增地址")
    @PostMapping("/add")
    @ApiImplicitParam(name = "address", value = "地址实体", required = true, dataType = "AddressReq")
    public JsonResult add(@Valid @RequestBody AddressReq address){
        Address address1 = new Address();
        User user = userService.getById(getUserId());
        Optional.ofNullable(user).orElseThrow(()-> new ServerInternalErrorException(ErrorEnum.NO_AUTH_OPERATION));
        //校验detail中是否还有省市区
        // pattern = "/.*?省.*?市.*?区$/";
        //boolean isMatch = Pattern.matches(pattern, address.getDetail());
        String summarys = addressResolution(address.getDetail());
        if(summarys != null && summarys.length() > 0){
            String detail = address.getDetail().replace(summarys, "");
            address.setDetail(detail);
            address.setSummary(summarys);
            //throw new ServerInternalErrorException(ErrorEnum.PARAM_VALID_ERROR);
        }
        BeanUtils.copyProperties(address,address1);
        address.setId(null);
        address1.setUserId(getUserId());
        address1.setCreateAt(new Date());
        address1.setDeleteState(Constant.DeleteStateEnum.NORMAL.getCode().shortValue());
        address1.setUserName(user.getUsername());
        Map map = new HashMap<String,String>();
        if(addressService.add(address1)){
            map.put("id",address1.getId().toString());
            return JsonResult.success(map);
        }else{
            return JsonResult.failure("操作失败");
        }
    }

    /**
     * 解析地址
     * @param address
     * @return
     */
    public static String addressResolution(String address){
        String regex="((?<province>[^省]+省|.+自治区)|上海|北京|天津|重庆)(?<city>[^市]+市|.+自治州)(?<county>[^县]+县|.+区|.+镇|.+局)?(?<town>[^区]+区|.+镇)?(?<village>.*)";
        Matcher m=Pattern.compile(regex).matcher(address);
        String province=null,city=null,county=null,town=null,village=null;
        //List<Map<String,String>> table=new ArrayList<Map<String,String>>();
       // Map<String,String> row=null;
        StringBuffer sb = new StringBuffer();
        while(m.find()){
            province=m.group("province");
            city=m.group("city");
            county=m.group("county");
            sb.append(province);
            sb.append(city);
            sb.append(county);
           /* row=new LinkedHashMap<String,String>();
            province=m.group("province");
            row.put("province", province==null?"":province.trim());
            city=m.group("city");
            row.put("city", city==null?"":city.trim());
            county=m.group("county");
            row.put("county", county==null?"":county.trim());
            town=m.group("town");
            row.put("town", town==null?"":town.trim());
            village=m.group("village");
            row.put("village", village==null?"":village.trim());
            table.add(row);*/
        }
        return sb.toString();
    }


    
    @ApiOperation(value = "根据Id删除地址", notes="根据Id删除地址")
    @GetMapping("/detete/{id}")
    @ApiImplicitParam(name = "id", value = "地址ID", required = true, dataType = "long",paramType = "path")
    public JsonResult delete(@PathVariable Long id, HttpServletRequest request){
        try {
            Address address = addressService.getById(id);
            if (!getUserId().equals(address.getUserId())){
                return JsonResult.failure("没有操作权限");
            }
            address.setDeleteState(Constant.DeleteStateEnum.DELETE.getCode().shortValue());
            addressService.update(address);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.failure("操作失败");
        }
        return JsonResult.success();
    }
	
    @ApiOperation(value = "根据ID获取地址", notes="根据ID获取地址")
    @GetMapping("/getById/{id}")
    @ApiImplicitParam(name = "id", value = "地址ID", required = true, dataType = "long",paramType = "path")
    public JsonResult<Address> getById(@PathVariable Long id, HttpServletRequest request){
    	Address address = addressService.getById(id);
        if (getUserId().equals(address.getUserId())){
            return JsonResult.failure("没有操作权限");
        }
        return JsonResult.success(address);
    }
    
}
